/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package formularios;

import Clases.AutoCompleteCombo;
import Clases.ComboBox;
import Clases.Tools;
import Clases.Transacciones;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.JTextComponent;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

/**
 *
 * @author Samuel
 */
public class Compras extends javax.swing.JInternalFrame {
    public static int IdMenu=7;
    private DefaultTableModel modelo;
     public JTable tabla;
     int _idbancos=0;
     int _idFormaPago=0;
     int _idArticulo =0;
     int _idEntidad =0;
     double _total =0;
      DecimalFormat df;
 
    /**
     * Creates new form Compras
     */
    public Compras() {
        initComponents();
        modelo = new DefaultTableModel();
        tabla = new JTable();
        df  = new DecimalFormat("0.00"); 
        CargarComboBancos();
        CargarComboFormaPago();
        ObtenerFechaActual();
        CargarComboArticulo();
        CargarComboEntidad();
        AgregarListenerComboArticulo();
        AgregarListenerComboFormaPago();
        AgregarListenerComboBancos();
        AgregarListenerComboEntidad();
        modeloTabla();
    }
//    
//    private void crearPartida()
//    {
//        try
//        {           
//            String strComando ="";
//            String resultado="";
//            String query ="";
//            int idmovcuenta =0;
//            int idcuenta = 0;
//            strComando="insert into movcuenta (fecha, tipo, id, observaciones, idusuario) "
//                + " values ('"+Tools.ObtenerFechaSql(jDateFecha.getDate())+"','movinventario',1,'movinventario',"+MainMenu.IdUsuario+")" ;
//            resultado=MainMenu.conexion.Ejecutar(strComando);
//            ResultSet rs = MainMenu.conexion.EjecutarConsulta("select max(idmovcuenta) from movcuenta");
//             if(rs.next()) 
//            {
//                idmovcuenta  = rs.getInt(1);               
//            }
//             if (resultado.equals(""))
//            {
//                for (int i = 0; i < modelo.getRowCount(); i++) 
//                {                    
//                    int idarticulo = Integer.valueOf(tabla.getValueAt(i, 0).toString());
//                    rs = MainMenu.conexion.EjecutarConsulta("select idcuentaingreso from articulos  where idarticulo =  "+idarticulo+"  ");
//                    if(rs.next()) 
//                    {
//                        idcuenta = rs.getInt(1);               
//                    }
//                    double total = Double.valueOf(tabla.getValueAt(i, 4).toString());
//                    String sql = ("insert into detallemovcuenta (idmovcuenta,idcuenta,debe,haber) "
//                    + "values ('"+idmovcuenta+"','"+idcuenta+"','"+total+"',0)");
//                    MainMenu.conexion.Ejecutar(sql);
//                    
//                    sql = ("update cuentas set saldo = saldo + "+total+" where idcuenta in ("+idcuenta+") ");
//                    MainMenu.conexion.Ejecutar(sql);
//                }
//                
////                cuadre(idmovcuenta);
//                
//            }
//        }
//        catch(Exception ex)
//        {
//             
//        }         
//    }

//    private void cuadre(int idmovcuenta)
//    {
//        try
//        { 
//            String query;
//            String resultado ="";
//            int banco = 5;
//       
//            resultado =MainMenu.conexion.Ejecutar( "insert into detallemovcuenta (idmovcuenta,idcuenta,debe,haber) "
//                    + " values ('"+idmovcuenta+"',5,'0','"+_total+"')" );
//            
//            String sql = ("update cuentas set saldo = saldo - "+_total+" where idcuenta in ("+banco+") ");
//            MainMenu.conexion.Ejecutar(sql);
//        }
//        catch(Exception ex)
//        {
//            JOptionPane.showMessageDialog(this, ex,"Información",JOptionPane.INFORMATION_MESSAGE); 
//        } 
//        
//    }

    private void Guardar()
    {
        Connection _conexion=null;
      try
        {    
            int idtipomov = 2;
            int idmov =0;                        
            String strComando ="";
            _idFormaPago=2;
            //Encabezado del movimiento inventario
            strComando="insert into movinventario (fecha, identidad, idformapago, idtipomov, "
                 + " idusuario, observaciones, norecibo, nocheque, idbanco) "
                 + "values ('"+Tools.ObtenerFechaSql(jDateFecha.getDate())+"', '"+ _idEntidad +"','"+ _idFormaPago +"' ,'"+ idtipomov +"', "
                        + " "+MainMenu.IdUsuario+",'"+ jTobservaciones.getText()+"','"+ jTRecibo.getText()+"','"+ jTCheque.getText()+"','"+  _idbancos +"' )" ;
            
            //inicio de transaccion
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            _conexion = DriverManager.getConnection("jdbc:mysql://"+MainMenu.server+"/"+MainMenu.dataBase,MainMenu.user, MainMenu.password);
            _conexion.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            _conexion.setAutoCommit(false);//Inicia la transaccion
            Statement st = _conexion.createStatement();
             
            st.execute( strComando,Statement.RETURN_GENERATED_KEYS);
            ResultSet rs = st.getGeneratedKeys();
            if(rs.next()) 
            {
                idmov = rs.getInt(1);               
            }
            //Detalle del movimiento invetnario
            for (int i = 0; i < modelo.getRowCount(); i++) 
            {
                int idarticulo = Integer.valueOf(tabla.getValueAt(i, 0).toString());
                double can = Double.valueOf(tabla.getValueAt(i, 2).toString());
                double monto = Double.valueOf(tabla.getValueAt(i, 3).toString());
                PreparedStatement pst = _conexion.prepareStatement("insert into detallemovinventario (idmov, idarticulo, cantidad, precio) VALUES  (?,?,?,?)");
                pst.setInt(1, idmov);
                pst.setInt(2, idarticulo);
                pst.setDouble(3, can );
                pst.setDouble(4,  monto );
                pst.execute();
            }
            
            //Creacion de partida
            String query ="";
            int idmovcuenta =0;
            int idcuenta = 0;
            String strComandoPartida="insert into movcuenta (fecha, tipo, id, observaciones, idusuario) "
                + " values ('"+Tools.ObtenerFechaSql(jDateFecha.getDate())+"','movinventario',1,'movinventario',"+MainMenu.IdUsuario+")" ;
      
            st.execute(strComandoPartida,Statement.RETURN_GENERATED_KEYS);
             ResultSet rs1 = st.getGeneratedKeys();

             if(rs1.next()) 
            {
                idmovcuenta = rs1.getInt(1);               
            }
            for (int i = 0; i < modelo.getRowCount(); i++) 
            {                    
                //Obteniendo el id de la cuenta del articulo
                int idarticulo = Integer.valueOf(tabla.getValueAt(i, 0).toString());
                rs = MainMenu.conexion.EjecutarConsulta("select idcuentaingreso from articulos  where idarticulo =  "+idarticulo+"  ");
                if(rs.next()) 
                {
                    idcuenta = rs.getInt(1);               
                }                    
                double total = Double.valueOf(tabla.getValueAt(i, 4).toString());
                //Inicio de transaccion del detalle de la cuenta
                PreparedStatement pst2 = _conexion.prepareStatement("insert into detallemovcuenta (idmovcuenta,idcuenta,debe,haber) values   (?,?,?,?)");
                pst2.setInt(1, idmovcuenta);
                pst2.setInt(2, idcuenta);
                pst2.setDouble(3, total );
                pst2.setDouble(4,  0 );
                pst2.execute();
                //inserta en el saldo de cada cuenta
                PreparedStatement pst3 = _conexion.prepareStatement("update cuentas set saldo = saldo + ? where idcuenta in (?)");
                pst3.setDouble(1, total );
                pst3.setInt(2, idcuenta);
                pst3.execute();
            }                 
            ///fin de la creacion de partida
            //cuadre de partida y saldos
            Statement stMovCuenta = _conexion.createStatement();
            int banco = 5;
            String insert = ("insert into detallemovcuenta (idmovcuenta,idcuenta,debe,haber) "
                    + " values ('"+idmovcuenta+"',5,'0','"+_total+"')" ); 
            //Actualiza el saldo
            String up = ("update cuentas set saldo = saldo - "+_total+" where idcuenta in ("+banco+") ");
            stMovCuenta.execute(insert);
            stMovCuenta.execute(up);
             //fin de cuadre
            _conexion.commit();
            
            JOptionPane.showMessageDialog(this, "Los datos se almacenaron correctamente","Información",JOptionPane.INFORMATION_MESSAGE);
            LimpiarVariables();
             
          }
        catch(Exception ex)
        {
            try {
                _conexion.rollback();
            } catch (SQLException ex1) {
                 
            }
        }  
    }
    
    private void LimpiarVariables()
    {
        limpiarTabla();
        jTRecibo.setText("");        
        jTCheque.setText("");
        jTobservaciones.setText("");
        jTCantiad.setText("0");
        jTMonto.setText("0.00");
        tfTotal.setText("0.00");
        CargarComboBancos();
        CargarComboFormaPago();
        CargarComboEntidad();
        CargarComboArticulo();
        ObtenerFechaActual();        
    }
    
    private void limpiardetalle()
    {
        CargarComboArticulo();
        jTCantiad.setText("0");
        jTMonto.setText("0.00");
    }
    
     private void CargarComboBancos()
    {
        DefaultComboBoxModel modelo = Clases.ComboBox.CargarCombo("SELECT idbanco id, nombre FROM coldb.bancos where debaja is null Order by nombre asc", MainMenu.conexion);
        cmbBancos.setModel(modelo);
        AutoCompleteDecorator.decorate(cmbBancos);
    }
     
     private void CargarComboEntidad()
    {
        DefaultComboBoxModel modelo = Clases.ComboBox.CargarCombo("SELECT identidad id, nombre FROM entidades where debaja is null and idtipoentidad = 3 order by nombre ASC", MainMenu.conexion);
        cmbEntidad.setModel(modelo);
        AutoCompleteDecorator.decorate(cmbEntidad);
    }
     
     private void CargarComboFormaPago()
    {
        DefaultComboBoxModel modelo = Clases.ComboBox.CargarCombo("SELECT idformapago id, nombre FROM coldb.formapago where debaja is null order by nombre ASC", MainMenu.conexion);
        cbFormaPago.setModel(modelo);
        AutoCompleteDecorator.decorate(cbFormaPago);
        cbFormaPago.setSelectedIndex(0);
    }
     
      private void CargarComboArticulo()
    {
        DefaultComboBoxModel modelo = Clases.ComboBox.CargarCombo("select idarticulo id, nombre from articulos where debaja is null order by nombre ASC", MainMenu.conexion);
        cbCompra.setModel(modelo);
        AutoCompleteDecorator.decorate(cbCompra);
    }
        
    private void ObtenerFechaActual()
    {
        jDateFecha.setDate(Transacciones.ObtenerFechaServidor(MainMenu.conexion));
    }
    
    public void limpiarTabla()
    {
        int a =modelo.getRowCount()-1;
        for(int i=a; i>=0;i--)
        {        
            modelo.removeRow(i );
        }
    }
    
    private void modeloTabla ()             
    {
        String[] columnNames = {"idServicio","Servicio","Cantidad","Precio","Total"};
        int[] OcultarColumas = {1};
        modelo.setColumnIdentifiers(columnNames);              
        modelo.setColumnCount(5);        
        modelo.setRowCount(0);               
        tabla.setModel(modelo);        
        tabla.setBounds(new Rectangle(10, 60, 510, 370));        
        jTdetalle.setModel(modelo);   
         //oculta las columnas 0, 1 , 2 , 3
        Hashtable ht = new Hashtable();
        ht.clear();
        ht.put(0, 0);
        ocultarColumnas (ht,jTdetalle);
    }
    
    private void ocultarColumnas(Hashtable no, JTable t)
    { 
        Enumeration e = no.elements();
        Object valor;
        while( e.hasMoreElements() )
        {
            valor = e.nextElement();
            int a = Integer.parseInt(valor.toString());
            t.getColumnModel().getColumn(a).setMinWidth(0);
            t.getColumnModel().getColumn(a).setMaxWidth(0);
            t.getColumnModel().getColumn(a).setWidth(0);
            t.getColumnModel().getColumn(a).setWidth(0);
        }
    }
    
    private boolean verificardetalle()
    {
        boolean resultado = true;
        if (jTCantiad.getText().equals(""))
            resultado = false;
        if (jTMonto.getText().equals(""))
             resultado = false;
        if (_idArticulo == 0)
            resultado=false;
        return resultado;
    }
    
    private boolean repetido(int id)
    {
        boolean r = false;
        int idarticulo;
        int row = jTdetalle.getRowCount();
        for (int y =0; y <row; y++)
        {
            idarticulo = Integer.valueOf(jTdetalle.getValueAt(y, 0).toString());
            if (idarticulo == id)
            {
                r = true;
            }
        }
        
        return r;
    }
    
    public void AgregarServicio()
    {
        _idArticulo = ((ComboBox) cbCompra.getSelectedItem()).getId();
        boolean resultado = verificardetalle();    
        boolean res = verificar();
        if (resultado == true && res == true)
        {
            int agregarRow = 0;
            int row = jTdetalle.getRowCount();
            boolean repetidos = true;
            
            double total =0;
             repetidos = repetido (_idArticulo);
            if (repetidos == false)
            {
                DefaultTableModel temp3 = (DefaultTableModel) jTdetalle.getModel();
                Object nuevo1[]= {temp3.getRowCount()+1,"",""};
                temp3.addRow(nuevo1); 
           
                jTdetalle.setValueAt(_idArticulo, row , 0);  
                jTdetalle.setValueAt(cbCompra.getModel().getSelectedItem().toString(), row , 1); 
                jTdetalle.setValueAt(jTCantiad.getText(), row , 2); 
                jTdetalle.setValueAt(jTMonto.getText(), row , 3); 
                try{ total = Double.valueOf(jTCantiad.getText().toString())  * Double.valueOf( jTMonto.getText().toString() ); } catch(Exception ex) { }
                 jTdetalle.setValueAt(String.valueOf(total), row , 4);     
               sumatotal();
                limpiardetalle();
            }
            if (repetidos == true)
                 JOptionPane.showMessageDialog(null, "El articulo ya fue agregado", "Información", JOptionPane.ERROR_MESSAGE);
                
        }
    }
    
    private void sumatotal()
    {
        int row= jTdetalle.getRowCount();
        double tTotal =0;
        for (int x =0; x<row; x++)
        {
            tTotal = (Double.valueOf(jTdetalle.getValueAt(x, 4).toString()) + tTotal);            
        }
        tfTotal.setText(df.format((tTotal)));
        _total = tTotal;
    }
    
    private void  EliminarServicio()
    {
        int row = jTdetalle.getSelectedRow();
        int answer = JOptionPane.showConfirmDialog(null, "Desea eliminar?", "Confirme por favor", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (answer == JOptionPane.YES_OPTION)
        {
            try
            {
                DefaultTableModel temp = (DefaultTableModel) jTdetalle.getModel();
                temp.removeRow(row);
                sumatotal();
                JOptionPane.showMessageDialog(null, "Dato Eliminado", "Información", JOptionPane.ERROR_MESSAGE);
            }
            catch(ArrayIndexOutOfBoundsException e)
            {
                
            }
        }
    }
     
    private void AgregarListenerComboBancos()
    {
        cmbBancos.addActionListener (new ActionListener () 
        {
            public void actionPerformed(ActionEvent e) 
            {
                try
                {
                    _idbancos = ((ComboBox) cmbBancos.getSelectedItem()).getId();
                }
                catch(Exception ex)
                {
                    
                }
            }
        });
    }
    
     private void AgregarListenerComboFormaPago()
    {
        cbFormaPago.addActionListener (new ActionListener () 
        {
            public void actionPerformed(ActionEvent e) 
            {
                try
                {
                    _idFormaPago = ((ComboBox) cbFormaPago.getSelectedItem()).getId();
                }
                catch(Exception ex){}
            }
        });
 
    }
     
      private void AgregarListenerComboArticulo()
    {
        cbCompra.addActionListener (new ActionListener () 
        {
            public void actionPerformed(ActionEvent e) 
            {
                try
                {
                    _idArticulo = ((ComboBox) cbCompra.getSelectedItem()).getId();
                }
                catch(Exception ex){}
            }
        });
   
    }
      
    private void AgregarListenerComboEntidad()
    {
        cmbEntidad.addActionListener (new ActionListener () 
        {
            public void actionPerformed(ActionEvent e) 
            {
                try
                {
                    _idEntidad = ((ComboBox) cmbEntidad.getSelectedItem()).getId();
                }
                catch(Exception ex){}
            }
        });
        
    }
       
    public boolean verificar()
    {
        boolean r = true;
        boolean resultado = validaNum(this.jTCantiad.getText());
        if (resultado == false)
        {
            JOptionPane.showMessageDialog(this, "Debe de ingresar solo numeros","Error",JOptionPane.ERROR_MESSAGE);
            r = false;
        }      
        resultado = validaNum(this.jTMonto.getText());
        if (resultado == false)
        {
               JOptionPane.showMessageDialog(this, "Debe de ingresar solo numeros","Error",JOptionPane.ERROR_MESSAGE);
               r = false;
        }
         if (_idArticulo == 0)
        {
               JOptionPane.showMessageDialog(this, "Debe de elegir un articulo","Error",JOptionPane.ERROR_MESSAGE);
               r = false;
        }
        return r;
       }
    
    public boolean verificarEncabezado()
    {
        boolean bandera = true;
        if (_idbancos==0)
            bandera= false;
        if(_idEntidad ==0)
            bandera = false;
//        if(_idFormaPago==0)
//            bandera= false;
        return bandera;
        
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelEncabezado = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jDateFecha = new com.toedter.calendar.JDateChooser();
        jLabel2 = new javax.swing.JLabel();
        cbFormaPago = new javax.swing.JComboBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTobservaciones = new javax.swing.JTextArea();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        cmbBancos = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        jTCheque = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        cmbEntidad = new javax.swing.JComboBox();
        jTRecibo = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTdetalle = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        btnAgregar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        jTMonto = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTCantiad = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        cbCompra = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jPanel5 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        tfTotal = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        btnNuevo = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();

        setClosable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Compras");

        panelEncabezado.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Fecha");

        jLabel2.setText("Forma de Pago");

        cbFormaPago.setEnabled(false);

        jTobservaciones.setColumns(20);
        jTobservaciones.setRows(5);
        jScrollPane2.setViewportView(jTobservaciones);

        jLabel7.setText("Observaciones");

        jLabel8.setText("Banco:");

        jLabel9.setText("No Cheque");

        jLabel11.setText("Proveedor");

        jLabel12.setText("No. Recibo");

        javax.swing.GroupLayout panelEncabezadoLayout = new javax.swing.GroupLayout(panelEncabezado);
        panelEncabezado.setLayout(panelEncabezadoLayout);
        panelEncabezadoLayout.setHorizontalGroup(
            panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelEncabezadoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelEncabezadoLayout.createSequentialGroup()
                        .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel8))
                        .addGap(18, 18, 18)
                        .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jDateFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cbFormaPago, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cmbBancos, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(97, 97, 97))
                    .addGroup(panelEncabezadoLayout.createSequentialGroup()
                        .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel11)
                            .addComponent(jLabel12))
                        .addGap(38, 38, 38)
                        .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTRecibo, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cmbEntidad, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel7)
                            .addComponent(jLabel9))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
                .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jTCheque)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE))
                .addGap(341, 341, 341))
        );
        panelEncabezadoLayout.setVerticalGroup(
            panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelEncabezadoLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel11)
                        .addComponent(jLabel9)
                        .addComponent(jTCheque, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(cmbEntidad, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelEncabezadoLayout.createSequentialGroup()
                        .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(panelEncabezadoLayout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(jLabel12))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelEncabezadoLayout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jTRecibo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel7))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jDateFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(cbFormaPago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelEncabezadoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel8)
                            .addComponent(cmbBancos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(panelEncabezadoLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        jTdetalle.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTdetalle);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/add24.png"))); // NOI18N
        btnAgregar.setText("Agregar");
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/delete24.png"))); // NOI18N
        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        jTMonto.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jTMonto.setText("0.00");

        jLabel6.setText("Monto");

        jTCantiad.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jTCantiad.setText("0");
        jTCantiad.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                jTCantiadCaretUpdate(evt);
            }
        });
        jTCantiad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTCantiadActionPerformed(evt);
            }
        });
        jTCantiad.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTCantiadKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTCantiadKeyTyped(evt);
            }
        });

        jLabel3.setText("Cantidad");

        jLabel4.setText("Compra");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbCompra, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTCantiad, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addGap(2, 2, 2)
                .addComponent(jTMonto, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnEliminar)
                .addGap(2, 2, 2)
                .addComponent(btnAgregar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cbCompra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4)
                        .addComponent(jLabel6)
                        .addComponent(jTMonto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jTCantiad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)
                        .addComponent(btnEliminar))
                    .addComponent(btnAgregar))
                .addGap(0, 0, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        tfTotal.setEditable(false);
        tfTotal.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        tfTotal.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        jLabel10.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel10.setText("Total");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tfTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addContainerGap(13, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jLabel10)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tfTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/add24.png"))); // NOI18N
        btnNuevo.setText("Nuevo");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/floppy24.png"))); // NOI18N
        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnNuevo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnGuardar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(btnNuevo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnGuardar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(panelEncabezado, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(panelEncabezado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
       AgregarServicio();
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
         EliminarServicio();
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        LimpiarVariables();
    }//GEN-LAST:event_btnNuevoActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        int answer=JOptionPane.showConfirmDialog(null, "¿Desea guardar la compra?", "Confirme por favor", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if(answer == JOptionPane.YES_OPTION)
        {
            try
            {
                _idbancos = ((ComboBox) cmbBancos.getSelectedItem()).getId();
                _idEntidad = ((ComboBox) cmbEntidad.getSelectedItem()).getId();
                boolean r = verificarEncabezado();
                int row = jTdetalle.getRowCount();
                if (r == true && row> 0)
                    Guardar();
                else
                    JOptionPane.showMessageDialog(this, "No debe de dejar campos en blanco","Error",JOptionPane.ERROR_MESSAGE);
            }
            catch(Exception ex)
            {
                JOptionPane.showMessageDialog(this, ex,"Error",JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    
    private void jTCantiadKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTCantiadKeyPressed
      
    }//GEN-LAST:event_jTCantiadKeyPressed

    private void jTCantiadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTCantiadActionPerformed
        
    }//GEN-LAST:event_jTCantiadActionPerformed

    private void jTCantiadCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_jTCantiadCaretUpdate
    // TODO add your handling code here:
    }//GEN-LAST:event_jTCantiadCaretUpdate

    private void jTCantiadKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTCantiadKeyTyped
              // TODO add your handling code here:
    }//GEN-LAST:event_jTCantiadKeyTyped

    public static boolean validaNum(String Valor) 
    {
        try 
        {
           // Integer.parseInt(Valor);
            Double.parseDouble(Valor);            
            return true;
        }
        catch (Exception e) 
        {
            return false;              
        }
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JComboBox cbCompra;
    private javax.swing.JComboBox cbFormaPago;
    private javax.swing.JComboBox cmbBancos;
    private javax.swing.JComboBox cmbEntidad;
    private com.toedter.calendar.JDateChooser jDateFecha;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTCantiad;
    private javax.swing.JTextField jTCheque;
    private javax.swing.JTextField jTMonto;
    private javax.swing.JTextField jTRecibo;
    private javax.swing.JTable jTdetalle;
    private javax.swing.JTextArea jTobservaciones;
    private javax.swing.JPanel panelEncabezado;
    private javax.swing.JTextField tfTotal;
    // End of variables declaration//GEN-END:variables
}
